package com.mybatis.test.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * 描述：Java 形式的配置类
 *
 * @author lida
 * @time 2019/11/30 11:32
 */
@Configuration
@ComponentScan("com.mybatis.test")
@MapperScan("com.mybatis.test.dao")
public class AppConfig {

	@Bean
	@Autowired
	public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		return sqlSessionFactoryBean;
	}

	@Bean
	@Autowired
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
		SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(Objects.requireNonNull(sqlSessionFactoryBean.getObject()));
		return sqlSessionTemplate;
	}

	/**
	 * 这里的配置写死了，实际的话可以从配置文件获取
	 * @return DataSource
	 */
	@Bean
	public DataSource dataSource(){
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
		druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/miaosha?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8");
		druidDataSource.setUsername("root");
		druidDataSource.setPassword("123456");
		return druidDataSource;
	}
}

